package com.yc.spring.jdbc.dao;

import com.yc.spring.jdbc.bean.Account;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@Repository
public class AccountDao {

    @Resource
    private JdbcTemplate jt;

    /**
     * 开户
     *
     * @param account
     */
    public void insert(Account account) {
        String sql = "insert into account values(?,?)";
        jt.update(sql, account.getAccountid(), account.getBalance());
    }

    /**
     * 只更新金额 , 在原金额上加减
     * 存款  正数
     * 取款  负数
     */
    public void updateBalance(Account account) {
        String sql = "update account set balance = balance + ? where accountid = ?";
        jt.update(sql, account.getBalance(), account.getAccountid());
    }

    /**
     * 根据银行账号查询
     *
     * @param accountid
     * @return
     */
    public Account selectById(Integer accountid) {
        String sql = "select * from account where accountid = ?";
        return jt.query(sql, rs -> {
            rs.next();
            Account a = new Account();
            a.setAccountid(rs.getInt("accountid"));
            a.setBalance(rs.getDouble("balance"));
            return a;
        }, accountid);
    }

    /**
     * 查询所有
     *
     * @return
     */
    public List<Account> selectAll() {
        String sql = "select * from account";
        return jt.query(sql, (rs, i) -> {
            Account a = new Account();
            a.setAccountid(rs.getInt("accountid"));
            a.setBalance(rs.getDouble("balance"));
            return a;
        });
    }


}
